package com.cgsd.heyu.utils;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.android.library.utils.ToastHelper;

/**
 * @author xiaoxing
 * Description 说明
 * CreateData: 2020/11/16
 */
public class AudioPlay {
    /**
     * 录音文件
     */
    private String audioFileName;

    /**
     * 录音播放器
     */
    private MediaPlayer mPlayer;

    /**
     * 录音是否暂停
     */
    private boolean isPlayerPause = false;

    /**
     * 录音是否还在播放
     * (播放中)
     */
    private boolean isAudioPlaying = false;
    /**
     * 监听
     */
    private AudioPlayListener audioPlayListener;
    /**
     * 创建子线程
     */
    private Handler mHandler;
    /**
     * 文件时长
     */
    private int maxTime;
    /**
     * 退出
     */
    private boolean isCancel;


    private Handler sHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bundle data = msg.getData();
            int currentPosition = data.getInt("currentPosition");
            if (!mPlayer.isPlaying()){
                return;
            }
            if(audioPlayListener != null){
                audioPlayListener.playProgress(maxTime,currentPosition);
            }
        }
    };

    public AudioPlay(AudioPlayListener audioPlayListener) {
        this.audioPlayListener = audioPlayListener;
        mPlayer = new MediaPlayer();
        checkOverAudio();
        updateAudioPro();
    }

    /**
     * 重新设置播放资源
     *
     * @param audioFileName
     */
    public void setAudioFileName(String audioFileName) {
        this.audioFileName = audioFileName;
        isAudioPlaying = false;
    }

    /**
     * 更新播放录音进度
     */
    private void updateAudioPro() {
        if (mPlayer == null) {
            return;
        }
        //获取总时长
        HandlerThread thread = new HandlerThread("MyHandlerThread");
        //创建一个HandlerThread并启动它
        thread.start();
        //使用HandlerThread的looper对象创建Handler，如果使用默认的构造方法，很有可能阻塞UI线程
        mHandler = new Handler(thread.getLooper());
        //将线程post到Handler中
        mHandler.post(mBackgroundRunnable);
    }


    /**
     * 实现耗时操作的线程
     */
    Runnable mBackgroundRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                while (!isCancel) {
                    if (mPlayer.isPlaying()) {
                        int currentPosition = mPlayer.getCurrentPosition();
                        Message message = Message.obtain();
                        message.what = 10000;
                        Bundle bundle = new Bundle();
                        bundle.putInt("currentPosition", currentPosition);
                        message.setData(bundle);
                        sHandler.sendMessage(message);
                    }
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };


    /**
     * 播放
     */
    public void play() {
        //播放完成，重新播放
        try {
            mPlayer.reset();
            //重新设置要播放的音频
            mPlayer.setDataSource(audioFileName);
            //预加载音频
            mPlayer.prepare();
            //开始播放
            mPlayer.start();
            //开始在播放中
            maxTime = mPlayer.getDuration();
            if (audioPlayListener != null) {
                audioPlayListener.startPlay();
            }
            isAudioPlaying = true;
        } catch (Exception e) {
            ToastHelper.showDefaultToast("播放音频失败");
            if (audioPlayListener != null) {
                audioPlayListener.stopPlay();
            }
        }
    }

    /**
     * 停止播放
     */
    public void stopPlay(){
        if (mPlayer == null) {
            return;
        }
        if (mPlayer.isPlaying()) {
            mPlayer.stop();
        }
        isAudioPlaying = false;
        if (audioPlayListener != null){
            audioPlayListener.playComplete();
        }
    }

    /**
     * 退出播放
     * 释放资源
     */
    public void cancelPlay() {
        isCancel = true;
        if (mPlayer == null) {
            return;
        }
        if (mPlayer.isPlaying()) {
            mPlayer.stop();//停止音频的播放
        }
        mPlayer.release();//释放资源
        mPlayer = null;
        sHandler.removeMessages(10000);
        //销毁线程
        mHandler.removeCallbacks(mBackgroundRunnable);
    }

    /**
     * 停止播放录音监听
     */
    private void checkOverAudio() {
        if (mPlayer != null) {
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    isAudioPlaying = false;
                    if (audioPlayListener != null){
                        audioPlayListener.playComplete();
                    }
                }
            });
        }
    }

    /**
     * 是否在播放中
     * @return
     */
    public boolean isAudioPlaying(){
        return isAudioPlaying;
    }

    /**
     * 获取音频时长
     */
    public int getMaxTime(){
        return maxTime / 1000;
    }

    public interface AudioPlayListener {
        /**
         * 暂停播放
         */
        void stopPlay();

        /**
         * 播放进度
         * @param maxLength 总时长
         * @param progress 当前播放时长
         */
        void playProgress(int maxLength, int progress);

        /**
         * 播放完成
         */
        void playComplete();
        /**
         * 开始播放
         */
        void startPlay();
    }
}
